<template>
  <el-aside
    :class="
      'layout-aside-' +
      config.layout.layoutMode +
      ' ' +
      (config.layout.shrink ? 'shrink' : '')
    "
  >
    <div class="fold" @click="onMenuCollapse" style="cursor: pointer">
      <div v-if="!config.layout.overviewCollapse">站点</div>
      <!-- <Menu @click="onMenuCollapse" style="width: 1.3em; height: 1.3em" /> -->
      <Icon
        size="15"
        name="fa fa-filter"
        style="cursor: pointer"
        title="关键词划过滤"
      />
    </div>
    <el-input
      v-if="!config.layout.overviewCollapse"
      v-model="filterText"
      placeholder="输入关键字进行过滤"
      style="background: whitesmoke"
    />
    <div style="width: 100%" v-if="!config.layout.overviewCollapse">
      <el-checkbox
        v-model="state.menuNodeAll"
        @change="handleCheckedTreeNodeAll($event, 'menu')"
        >全选/全不选</el-checkbox
      >
      <el-checkbox
        v-model="state.menuCheckStrictly"
        @change="handleCheckedTreeConnect($event, 'menu')"
        >父子联动</el-checkbox
      >
    </div>
    <el-scrollbar ref="verticalMenusRef" class="vertical-menus-scrollbar">
      <el-tree
        v-if="!config.layout.overviewCollapse"
        ref="treeRef"
        class="filter-tree"
        :data="state.siteOptions"
        :props="defaultProps"
        node-key="siteId"
        :check-strictly="!state.menuCheckStrictly"
        :default-checked-keys="state.AllCheckedKeys"
        show-checkbox
        default-expand-all
        empty-text="加载中，请稍候"
        @check="handleCheckChange"
        :filter-node-method="filterNode"
      />
    </el-scrollbar>
  </el-aside>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed, watch, reactive, inject } from "vue";
import { ElTree, ElScrollbar } from "element-plus";
import { DictOperation } from "@/utils/common"; // 导入表格api方法生成器
// import type baTableClass from "@/utils/baTable";

interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();
const config = inject("config") as any;
const site = inject("site") as any;
const dictionary = inject("dictionary") as any;

//初始化字典处理类
const dictOperation = new DictOperation();
//重写字典处理
class NewDictOperation extends DictOperation {
  //获取字典
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象
    dictStore: string //仓库存储的原始字典数组
  ) => {
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      dictionary.getDictInfo(dictText).then((res: any) => {
        let tempTags = dictOperation.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state[dictStore] = res;
          getSiteList(); //获取站点数据
        });
      });
    } else {
      getSiteList(); //获取站点数据
    }
  };
}
const newDictOperation = new NewDictOperation();

//获取滚动条组件的ref
const verticalMenusRef = ref<InstanceType<typeof ElScrollbar>>();
// const baTable = inject("baTable") as baTableClass;

const defaultProps = {
  children: "children",
  label: "siteName",
  value: "siteName",
};

// 关键词过滤
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.siteName.includes(value);
};

const state: {
  regionOptions: anyObj[];
  stationOptions: anyObj[];
  siteOptions: anyObj[];
  menuNodeAll: boolean;
  menuCheckStrictly: boolean;
  AllCheckedKeys: any[];
} = reactive({
  regionOptions: [], //区域列表
  stationOptions: [], //工作中心列表
  siteOptions: [], //站点列表
  menuNodeAll: false,
  menuCheckStrictly: true,
  AllCheckedKeys: [],
});

// 传递给父组件的值
const emit = defineEmits(["on-chooseRegion"]);
//选择区域后调取区域数据展示
const handleCheckChange = (row: any, node: any) => {
  console.log("row", row, "node", node);
  emit("on-chooseRegion", row, node);
};

// 控制菜单是否折叠
const onMenuCollapse = () => {
  config.overViewsetLayout("overviewCollapse", !config.layout.overviewCollapse);
};

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  //加了针对站点树的配置选项距离
  let checkoutHeight = 32;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return (
      "calc(100vh - " + (172 + menuTopBarHeight + checkoutHeight - 60) + "px)"
    );
  } else {
    return (
      "calc(100vh - " + (140 + menuTopBarHeight + checkoutHeight - 60) + "px)"
    );
  }
});

const menuWidth = computed(() => config.overviewMenuWidth());

// 站点树全选
const getCheckeds = () => {
  return treeRef.value
    ?.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  //原始区域数据
  treeRef.value!.setCheckedNodes(value ? site.originData : []);
  emit("on-chooseRegion", getCheckeds());
};
// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  state.menuCheckStrictly = value ? true : false;
};

//获取机柜管理中站点类型为机柜的的字典值
const getDistrictNum = (val: string) => {
  let len = site.type.length;
  for (let i = 0; i < len; ) {
    if (site.type[i].dictLabel === val) {
      return site.type[i].dictValue - 0;
    } else {
      i++;
    }
  }
};

//获取第一级站点
const getDefaultType = (filter: any) => {
  let len = filter.length;
  let keys: any = [];
  for (let i = 0; i < len; i++) {
    if (filter[i].siteType === getDistrictNum("地区")) {
      if (filter[i].children && filter[i].children.length > 0) {
        keys.push(filter[i].siteId, ...getDefaultType(filter[i].children));
      } else {
        keys.push(filter[i].siteId);
      }
    }
  }
  return keys;
};

//获取全部地区站点数据
const getAllCheckKeys = (filter: any) => {
  let len = filter.length;
  let keys: any = [];
  for (let i = 0; i < len; i++) {
    keys.push(filter[i].siteId);
  }
  return keys;
};
//获取站点数据
const getSiteList = () => {
  site
    .getAllChoose({ siteTypes: [getDistrictNum("地区")] }, {}, false)
    .then(async (res: any) => {
      console.log("site.AllCheckedNodes", site.AllCheckedNodes);
      state.AllCheckedKeys = await getAllCheckKeys(site.AllCheckedNodes);
      //获取侧边站点树数据
      state.siteOptions = res;
      emit(
        "on-chooseRegion",
        {},
        {
          checkedKeys: state.AllCheckedKeys,
        }
      );
    })
    .catch((err: any) => {});
};

//获取机柜类型字典
const getDictionary = () => {
  //获取站点类型的字典
  newDictOperation.getDictionary(site, "sys_site_type", "siteType", "type");
};
getDictionary();

onMounted(() => {});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
defineExpose({
  getDefaultType,
});
</script>
<style lang="scss" scoped>
.layout-aside-Default {
  background-color: #fff;
  background: var(--ba-bg-color-overlay);
  margin: 0;
  height: calc(100vh - 81px);
  box-shadow: var(--el-box-shadow-light);
  border-radius: var(--el-border-radius-base);
  overflow: hidden;
  transition: width 0.3s ease;
  width: v-bind(menuWidth);
  .vertical-menus-scrollbar {
    height: v-bind(overviewMenusScrollbarHeight);
    // overflow-x: scroll;
    .filter-tree {
      display: inline-block;
    }
  }

  .fold {
    width: 100%;
    height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
  }
}

.layout-aside-Classic {
  background: var(--ba-bg-color-overlay);
  margin: 0;
  height: 85%;
  overflow: hidden;
  transition: width 0.3s ease;
  width: v-bind(menuWidth);

  .vertical-menus-scrollbar {
    height: v-bind(overviewMenusScrollbarHeight);
    // overflow-x: scroll;
    .filter-tree {
      display: inline-block;
    }
  }

  .fold {
    width: 100%;
    height: 40px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
  }
}
</style>
